import sqlite3
from datetime import datetime, timedelta
import os
import sys
import time
import signal
import threading

# 定义触发时间点（17:00）
TRIGGER_HOUR = 14
TRIGGER_MINUTE = 7

# 移除了 chinese_calendar 的导入，使用 Python 标准库实现工作日判断


def is_trade_day(now = None): 
    if now is None:
        now = datetime.now()
    # now = datetime.now() - timedelta(days=9)#for test
    # print(f"current: {now}")
    print(f"current date: {now.date()} weekday: {now.weekday()+1}")
    # print(f"time: {now.time()}")
    # weekday() 返回 0-6 (周一到周日), 所以 +1 后是 1-7 (周一到周日)
    if now.weekday()+1 in [1, 3, 5]:  # 修改为周一、周三、周五
        print(f"weekday...{now.weekday()+1}")
        # 简单判断，周一到周五为工作日（不考虑节假日）
        if now.weekday() < 5:  # 0-4 代表周一到周五
            print("workday")
            return 1
        else:
            print("holiday ")
            return 0
    else:
        return 0

        
def work_run(func):
    """
    装饰器函数，用于循环运行指定函数
    每3秒检查一次时间，在设定的时间点产生信号
    支持Ctrl+C优雅退出
    """
    # 用于控制循环的标志
    running = True
    
    def signal_handler(sig, frame):
        nonlocal running
        print("\n接收到退出信号，正在停止...")
        running = False
    
    # 注册信号处理器以捕获Ctrl+C
    signal.signal(signal.SIGINT, signal_handler)
    
    print(f"开始循环运行，将在每天 {TRIGGER_HOUR:02d}:{TRIGGER_MINUTE:02d} 触发，按Ctrl+C退出")
    
    last_minute = None
    # 计算触发时间点的分钟数 (小时*60 + 分钟)
    trigger_time_minutes = TRIGGER_HOUR * 60 + TRIGGER_MINUTE
    # 计算触发前一分钟的分钟数
    minute_before_trigger = trigger_time_minutes - 1
    
    while running:
        try:
            now = datetime.now()
            current_minute = now.hour * 60 + now.minute  # 将小时转换为分钟数
            
            # 检查是否从触发前一分钟穿越到触发时间点
            if (last_minute is not None and 
                last_minute == minute_before_trigger and 
                current_minute == trigger_time_minutes):
                print(f"时间穿越信号产生: {now.strftime('%Y-%m-%d %H:%M:%S')}")
                # 在这里调用传入的函数
                func()
            
            last_minute = current_minute
            
            # 等待3秒
            time.sleep(3)
            
        except Exception as e:
            print(f"运行出错: {e}")
            if running:
                time.sleep(3)  # 出错后继续等待
                
    print("程序已退出")


# 测试函数
def test_function():
    print("测试函数被调用！")


if __name__ == "__main__":
    # 运行工作日判断
    # is_trade_day()
    
    # 示例：使用 work_run 装饰器运行测试函数
    work_run(test_function)